# -*- coding: utf-8 -*-
"""
Created on Tue Aug 25 14:26:06 2015

@author: fg086897
"""
from PyQt5.QtGui import QTextCursor

import DsPackage
from DsSerial import DsSerial
import serial

from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtCore import pyqtSignal
from DreamSerial_UiHandler import DreamSerial_UiHandler
import logging
from TinaUtils import TinaUtils
import Utils
import json

logger = logging.getLogger('main.MainWindow')


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self)

        logger.info('Main Window logger start')
        self.ui = DreamSerial_UiHandler()
        self.flags = {"__isopen__": False, "__datatype__": "ascii"}
        self.ui.setupUi(self)
        self.serial = DsSerial()
        self.createActions()

    def closeEvent(self, e):
        """
        This will called when user close the window. save the configurations here.
        :param e:
        :return: Nothing
        TODO: Can this be placed in a better place?
        """
        if self.flags["__isopen__"]:
            self.serial.terminate()
        port = self.ui.cbbPortName.currentText()
        baud = int(self.ui.cbbBaudRate.currentText())
        rxHex = bool(self.ui.cbRxHex.isChecked())
        rxAscii = bool(self.ui.cbRxAscii.isChecked())
        txNewLine = bool(self.ui.cbNewLine.isChecked())
        config = {'port': port, 'rxHex': rxHex, 'txNewLine': txNewLine, 'rxASCII': rxAscii, 'baud': baud}
        configFile = json.dumps(config)
        try:
            f = open("config.json", 'w')
            f.write(configFile)
        finally:
            f.close()

        e.accept()

    def createActions(self):
        """
        Create actions and connection of all Qt widgets
        :return:
        """
        self.ui.pbOpenPort.clicked.connect(self.__onOpenPort)
        self.ui.pbSend.clicked.connect(self.__onSendData)
        self.ui.pbAddSignal.clicked.connect(self.__onAddSignal)
        self.ui.pbRmSignal.clicked.connect(self.__onDelSignal)
        self.ui.pbReadAllReg.clicked.connect(self.__onReadAllReg)
        self.ui.pbReadReg.clicked.connect(self.__onReadReg)
        self.serial.received.connect(self.ui.onRecvData)

    def __onOpenPort(self, settings=None):
        if not settings:
            settings = self.ui.getPortSettings()
        self.serial.open(settings)
        self.serial.start()

    def __onSendData(self):
        logger.info("Send Data Clicked")
        #        data, type = self.ui.getDataAndType()
        #        self.ui.onSendData(data, type)
        #        dataArray = Utils.getByteArray(data,type)
        dataArray = self.ui.onSendData(None)
        logger.info(dataArray)
        self.serial.send(dataArray)

    def __onReadAllReg(self):
        logger.info('Read all register')

    def __onReadReg(self):
        logger.info('Read register')
        address = int(self.ui.sbStartAddress.text())
        length = int(self.ui.sbReadLength.text())
        self.ui.cbbTxType.setCurrentIndex(1)
        tina = TinaUtils()
        cmdArray = tina.generateReadRegsCommand(address, length)
        cmdStr = " ".join(map(lambda b: format(b, "#02x"), cmdArray))
        self.ui.leTx.clear()
        self.ui.leTx.insert(cmdStr)

    def __onAddSignal(self):
        logger.info("Add new signal")
        self.ui.pteRx.moveCursor(QTextCursor.End)
        self.ui.pteRx.insertPlainText('Hello')

    def __onDelSignal(self):
        logger.info("Del signal")

    def __openPort(self, settings):
        DsSerial.open(settings)

    def __closePort(self, settings):
        DsSerial.close()
